package com.tbit.uqbike.client.remote.zfb.util;

import lombok.extern.slf4j.Slf4j;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

@Slf4j
public class SignUtils {

    private static final String ALGORITHM = "RSA";

    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static String getAlgorithms(boolean rsa2) {
        return rsa2 ? SIGN_SHA256RSA_ALGORITHMS : SIGN_ALGORITHMS;
    }

    public static String sign(String content, String privateKey, boolean rsa2) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    Base64.decode(privateKey));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature.getInstance(getAlgorithms(rsa2));

            signature.initSign(priKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));

            byte[] signed = signature.sign();

            return Base64.encode(signed);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    public static void main(String[] args) {

        String s = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlcQMS5IbDd1XGqBB4xYHU7D9DPc3WrTY3WYHlnq3+2JCjLpsurtveE/DY6R2ntO4S7U+er0GksraNeyZT0FViwTRxKzBrVVooaqV8qI0wWRd1m8HCvCClyxndWg06OGRy4LvJrsEmAPWJVs6ELlAyYSkWpXP3HqV3cFbk3sdy9reeyIrlFEUUAz8Mn7u4k94j/VYMAz2hETDe9A2+S+UKPjANqvI8wl/aO5vBkxcN0JfQUP8WIUXg/Ko1Rm4B1ygSxzjvYkUk/WF5FnZnL2IgvLfQw5oKJ56q3dFLGpAm9/DD8q3gbcb6vmKuX4FEkQYom9Zjcx/GvVchvIk4aQqFQIDAQAB";
        String s1 = sign("123154325356", s, true);
        System.out.println(s1);
    }

}
